<script lang="ts" setup>
import type { FormInstance } from 'element-plus';

import { ref } from 'vue';

import { ElMessage } from 'element-plus';

import {
  addGroup,
  deleteGroup,
  editGroup,
  reqGroupList,
} from '#/api/exchange-center';

interface Group {
  id: number;
  name: string;
}

const groupList = ref<Group[]>([]);
const getGroupList = async () => {
  try {
    const res = await reqGroupList();
    groupList.value = res.list;
  } catch (error) {
    handleError(error);
  }
};

const reqDeleteGroup = async ({ id }: { id: number }) => {
  try {
    await deleteGroup(id);
    getGroupList();
    ElMessage({
      message: '操作成功',
      type: 'success',
    });
  } catch (error) {
    handleError(error);
  }
};

const dialogFormVisible = ref(false);
const formRef = ref<FormInstance>();
const groupForm = ref<Group>({ id: 0, name: '' });

const rules = {
  name: [{ required: true, message: '请输入名称', trigger: 'blur' }],
};

const DIALOG_TYPE_ADD = 1;
const DIALOG_TYPE_EDIT = 2;

const dialogType = ref(DIALOG_TYPE_ADD);
const dialogTitle = ref('');

const openDialog = (type: number, data?: Group) => {
  dialogType.value = type;
  dialogTitle.value = type === DIALOG_TYPE_ADD ? '新增' : '编辑';

  if (type === DIALOG_TYPE_EDIT && data) {
    groupForm.value = { ...data };
  }
  dialogFormVisible.value = true;
};

const submitDialog = async (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  await formEl.validate(async (valid) => {
    if (valid) {
      try {
        await (dialogType.value === DIALOG_TYPE_ADD
          ? addGroup({ name: groupForm.value.name })
          : editGroup(groupForm.value.id, { name: groupForm.value.name }));
        formEl.resetFields();
        getGroupList();
        ElMessage({
          message: '操作成功',
          type: 'success',
        });
      } catch (error) {
        handleError(error);
      }
      dialogFormVisible.value = false;
    }
  });
};

const handleError = (error: any) => {
  ElMessage({
    message: `操作失败: ${error.message}`,
    type: 'error',
  });
};

getGroupList();
</script>

<template>
  <el-card>
    <div class="flex items-center justify-between">
      <span>组别设置</span>
      <el-button type="primary" @click="openDialog(DIALOG_TYPE_ADD)">
        新增
      </el-button>
    </div>
    <el-table :data="groupList" style="width: 100%">
      <el-table-column prop="id" label="ID" width="180" />
      <el-table-column prop="name" label="GroupName" width="180" />
      <el-table-column fixed="right" label="Operations" min-width="120">
        <template #default="{ row }">
          <el-button
            link
            type="primary"
            size="small"
            @click="openDialog(DIALOG_TYPE_EDIT, row)"
          >
            编辑
          </el-button>
          <el-popconfirm
            title="确定要删除当前组吗?"
            @confirm="reqDeleteGroup(row)"
          >
            <template #reference>
              <el-button link type="primary" size="small">删除</el-button>
            </template>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>

    <el-dialog v-model="dialogFormVisible" :title="dialogTitle" width="500">
      <el-form
        :model="groupForm"
        label-width="70px"
        :rules="rules"
        ref="formRef"
      >
        <el-form-item label="ID" v-if="dialogType === DIALOG_TYPE_EDIT">
          <el-input
            v-model="groupForm.id"
            autocomplete="off"
            disabled
            style="width: 40px"
          />
        </el-form-item>
        <el-form-item label="Name" prop="name">
          <el-input v-model="groupForm.name" autocomplete="off" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogFormVisible = false">取消</el-button>
          <el-button type="primary" @click="submitDialog(formRef)">
            保存
          </el-button>
        </div>
      </template>
    </el-dialog>
  </el-card>
</template>
